//
//  WBStatusListViewModel.m
//  WeiBoOC
//
//  Created by 韩菲菲 on 16/8/13.
//  Copyright © 2016年 韩菲菲. All rights reserved.
//

#import "WBStatusListViewModel.h"
#import "WBNetworkTool.h"
#import "WBStatusViewModel.h"

@interface WBStatusListViewModel ()


@end

@implementation WBStatusListViewModel

#pragma mark - 懒加载数组属性
- (NSMutableArray<WBStatusViewModel *> *)dataArray
{
    if(!_dataArray)
    {
        
        _dataArray = [NSMutableArray array];
    
    }
    
    return _dataArray;

}

#pragma mark - 请求数据
- (void)loadHomeDataWithFinishPullUp:(BOOL)isPullUp andBlock:(void(^)(BOOL isSuccess))finish
{
    /*
     since_id若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0。
     max_id若指定此参数，则返回ID小于或等于max_id的微博，默认为0。
     */
    int64_t sinceId = 0;
    int64_t maxId = 0;
    
    if(isPullUp)
    {
        //是上拉加载更多
        if(self.dataArray.count > 0){
            
            maxId = self.dataArray.lastObject.statusModel.sinaId - 1;

        }
        
    }else
    {
        //是下拉刷新
        sinceId = self.dataArray.firstObject.statusModel.sinaId;
    
    }
    
    [[WBNetworkTool sharedWBNetworkTool] getHomeDataWithMaxId:maxId andSinceId:sinceId andSuccess:^(id responseObject) {
        
        //遍历数组 字典转模型 创建模型
        NSArray *arr = responseObject[@"statuses"];
        
        
        //创建可变数组
        NSMutableArray *arrM = [NSMutableArray array];
        
        for (NSDictionary *dict in arr) {
            
            //创建模型
            WBStatusModel *model = [WBStatusModel statusModelWithDictionary:dict];

            
            WBStatusViewModel *viewModel = [WBStatusViewModel statusViewModelWithStatusModel:model];
            
            
            //添加到可变数组中
            [arrM addObject:viewModel];
            
        }
        
        if(isPullUp)
        {
            //是上拉加载更多
            [self.dataArray addObjectsFromArray:arrM.copy];
            
            NSLog(@"%lu",self.dataArray.count);
            
        }else
        {
            //是下拉刷新
            [arrM addObjectsFromArray:self.dataArray];
            
            self.dataArray = arrM;
            
        }
        
        NSLog(@"数据请求成功%lu",self.dataArray.count);
        
        //回调block 告诉控制器数据请求成功
        finish(YES);

        
    } andFailure:^(NSError *error) {
        
        NSLog(@"数据请求失败");
        finish(NO);
        
        
        
    }];
    
}

@end
